package com.example.demo.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * @Author YuanYuan
 * @Date 2024/5/7
 * @Time 10:26
 */

@ControllerAdvice
@ResponseBody//表示当前的所有方法返回的都是数据
public class MyExHandler {
   /**
    * 拦截所有的空指针异常，进行统一的数据返回
    * @return java.util.HashMap<java.lang.String,java.lang.Object>
   */
   //添加方法@ExceptionHandler 来订阅异常
   @ExceptionHandler(NullPointerException.class)
   public HashMap<String,Object> nullException(NullPointerException e){
      HashMap<String,Object> result = new HashMap<>();
      result.put("code","-1");
      result.put("msg","空指针异常:"+e.getMessage());
      result.put("data",null);
      return result;
   }

   @ExceptionHandler(Exception.class)
   public HashMap<String,Object> exException(Exception e){
      HashMap<String,Object> result = new HashMap<>();
      result.put("code","-1");
      result.put("msg","异常:"+e.getMessage());
      result.put("data",null);
      return result;
   }

}
